#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/device.h>


static unsigned int dev_major = 250;
static struct class *devcls;
static struct device *dev;

ssize_t chr_drv_read(struct file *fp, char __user *data, size_t count, loff_t *fpos)
{
    printk("chr_drv_read()\n");
    // int kernel_val = 555;
    // int ret = copy_to_user(data, &kernel_val, count);
    
    return 0;
}

ssize_t chr_drv_write(struct file *fp, const char __user *buf, size_t count, loff_t *fpos)
{
    printk("chr_drv_write()\n");
    // int value;
    // int ret = copy_from_user(&value, buf, count);
    // printk("receive data:%d\n", value);
    
    return 0;
}

int chr_drv_open(struct inode *inode, struct file *fp)
{
    printk("chr_drv_open()\n");
    return 0;
}

int chr_drv_close(struct inode *inode, struct file *fp)
{
    printk("chr_drv_close()\n");
    return 0;
}

const struct file_operations myfops = {
    .open = chr_drv_open,
    .read = chr_drv_read,
    .write = chr_drv_write,
    .release = chr_drv_close,
};

static int __init chr_dev_init(void)
{
    //申请设备号。
    int ret = register_chrdev(dev_major, "chr_dev_test", &myfops);
    
    //创建设备节点。
    devcls = class_create(THIS_MODULE, "chr_cls");
    
    dev = device_create(devcls, NULL, MKDEV(dev_major, 0), NULL, "chr2");
    
    return ret;
}

static void __exit chr_dev_exit(void)
{
    //释放设备节点。
    device_destroy(devcls, MKDEV(dev_major, 0));
    class_destroy(devcls);
    
    //释放申请的设备号。
    unregister_chrdev(dev_major, "chr_dev_test");
}

module_init(chr_dev_init);
module_exit(chr_dev_exit);
MODULE_LICENSE("GPL");

